package com.spica.spicaschool.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.widget.FrameLayout;

/**
 * @ClassName AndroidBug5497Workaround
 * @Description TODO
 * @Author Spica2 7
 * @Date 2021/2/28 10:15
 */
public class FixAndroidKeybord {


    public static void assistActivity(Activity activity) {
        new FixAndroidKeybord(activity);
    }

    private Context context;

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;

    private FixAndroidKeybord(Activity activity) {
        context = activity;
        FrameLayout content = activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(() -> possiblyResizeChildOfContent());
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }


    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight(context);
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                // 软键盘开始出现
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // 软键盘开始隐藏
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight(Context context) {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        //+StatusBarTool.getStatusBarHeight(context)
        return (r.bottom - r.top );
    }

    
}
